package com.leyou.cart.service;

import com.leyou.cart.pojo.Cart;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.JsonUtils;
import com.leyou.common.utils.UserHolder;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 虎哥
 */
@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String KEY_PREFIX = "cart.add.uid:";

    public void addCartItem(Cart cart) {
        // 1.获取用户
        Long userId = UserHolder.getUserInfo().getId();
        // 2.获取hash的操作对象  key  hashKey  value
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(KEY_PREFIX + userId);
        // 3.判断到底是新增还是修改
        String skuId = cart.getSkuId().toString();
        cart = handleCartItem(hashOps, cart);
        // 5.写到redis
        hashOps.put(skuId, JsonUtils.toString(cart));
    }

    private Cart handleCartItem(BoundHashOperations<String, String, String> hashOps, Cart cart){
        // 3.判断要添加的商品是否存在
        String skuId = cart.getSkuId().toString();
        Boolean exists = hashOps.hasKey(skuId);
        if(BooleanUtils.isTrue(exists)) {
            // 4.存在，修改数量
            Integer newNum = cart.getNum();
            // 4.1.获取旧的
            String json = hashOps.get(skuId);
            cart = JsonUtils.toBean(json, Cart.class);
            // 4.2.修改数量
            cart.setNum(cart.getNum() + newNum);
        }
        return cart;
    }

    public List<Cart> queryCartList() {
        // 1.获取用户
        Long userId = UserHolder.getUserInfo().getId();
        // 2.获取hash的操作对象  key  hashKey  value
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(KEY_PREFIX + userId);
        // 3.判断购物车是否为空
        Long size = hashOps.size();
        if(size == null || size == 0){
            // 不存在，返回404
            throw new LyException(ExceptionEnum.DATA_NOT_FOUND);
        }
        // 4.查询
        List<String> values = hashOps.values();
        if(CollectionUtils.isEmpty(values)){
            // 不存在，返回404
            throw new LyException(ExceptionEnum.DATA_NOT_FOUND);
        }
        // 5.把查询到的JSON转为Cart集合
        List<Cart> carts = new ArrayList<>();
        for (String value : values) {
            carts.add(JsonUtils.toBean(value, Cart.class));
        }
        return carts;
    }

    public void addCartItemList(List<Cart> cartItems) {
        // 1.获取用户
        Long userId = UserHolder.getUserInfo().getId();
        // 2.获取hash的操作对象  key  hashKey  value
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(KEY_PREFIX + userId);

        // 3.创建一个map，存放skuId和cart的键值对，批量新增
        Map<String,String> carts = new HashMap<>();
        // 4.处理cart，
        for (Cart cartItem : cartItems) {
            // 判断是否存在，如果存在，会累加数量
            Cart cart = handleCartItem(hashOps, cartItem);
            // 写入map
            carts.put(cart.getSkuId().toString(), JsonUtils.toString(cart));
        }

        // 4.一次写入
        hashOps.putAll(carts);
    }
}
